package com.lf.web.service.system.user;

import com.lf.data.Cluster;
import com.lf.data.ClusterUtil;
import com.lf.data.Validate;
import com.lf.data.search.Field;
import com.lf.data.search.Query;
import com.lf.web.service.ResponseCode;
import com.lf.web.service.ResponseInfo;
import com.lf.web.service.ServiceSupport;
import com.lf.web.service.system.role.Role;
import com.lf.web.service.system.role.RoleDAO;
import org.apache.log4j.Logger;

import java.util.Date;
import java.util.List;

public class UserAddService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(UserAddService.class);
    private UserDAO userDAO;
    private RoleDAO roledao;
    private List<Cluster> roles = null;
    private String type = "";
    private User user = new User();

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void setRoledao(RoleDAO roledao) {
        this.roledao = roledao;
    }

    public String execute() {
        type = form.getString("type");
        switch (type) {
            case "save":
                return save();
            case "userName":
                return checkUsername();
            default:
                return add();
        }
    }

    private String checkUsername() {
        String userName = form.getString("userName");
        if (Validate.check("^[\\w\\d]{3,20}$", userName)) {
            Query query = new Query();
            query.eq(User.USER_NAME, userName);
            long count = userDAO.count(query);
            ResponseInfo rj = new ResponseInfo();
            rj.put("count", count);
            out(rj.toString());
        } else {
            LOGGER.error("检查非法用户名：" + userName);
            error(404);
        }
        return NONE;
    }

    private String add() {
        Field field = new Field();
        field.exclude(Role.LIMIT);
        roles = roledao.find(null, field, null);
        context.put("roles", roles);
        context.put("check", ClusterUtil.getCheck(User.class));
        return ADD;
    }

    private String save() {
        boolean check = form.getCluster(user);
        LOGGER.debug("添加用户信息：" + user);
        if (check) {
            ResponseInfo rj = new ResponseInfo();
            Query query = new Query();
            query.eq(User.USER_NAME, user.getString(User.USER_NAME));
            long count = userDAO.count(query);
            if (count > 0) {
                rj.setCode(ResponseCode.REPEAT);
                LOGGER.warn("插入用户名重复的用户信息：" + user);
            } else {
                String id = user.setId();
                user.put(User.CREATED, new Date());
                userDAO.insert(user);
                rj.setCode(ResponseCode.FINISH);
                rj.put("id", id);
            }
            out(rj);
        } else {
            error(404);
            LOGGER.error("非法添加用户信息：" + user);
        }
        return NONE;
    }

}
